package com.yunshang.wechat.service;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.yunshang.wechat.entity.RequestEntity;
import com.yunshang.wechat.entity.RequestVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

@Service
@Slf4j
public class WechatFunctionService {
    @Autowired
    private RequestService requestService;

    public String wechatFunction(RequestVo requestVo) throws Exception {
        //解析入参
        Gson gson = new Gson();
        String requestString = gson.toJson(requestVo);
        /*
         * 解析之前：RequestVo(prompt=22222, userId=99, accessKey=44444444, requestId=123123)
         * 解析之后：入参:{"prompt":"22222","userId":"99","accessKey":"44444444","requestId":"123123"}
         * */
        System.out.println("入参:" + requestString);
        // 调用的 API 地址
        String api = "http://aicodingtool.com.cn/api/insurchat";
        // 发送 HTTP 请求
        URL url = new URL(api);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json; utf-8");
        con.setRequestProperty("Accept", "application/json");
        con.setDoOutput(true);
        String jsonInput = requestString;
        try (OutputStream os = con.getOutputStream()) {
            byte[] input = jsonInput.getBytes("utf-8");
            os.write(input, 0, input.length);
        }
        // 处理返回的 JSON 数据
        String hobbyName = null;
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(con.getInputStream(), "utf-8"))) {
            StringBuilder response = new StringBuilder();
            String responseLine = null;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            String responesString = response.toString();
            gson = new Gson();
            JsonObject obj = gson.fromJson(responesString, JsonObject.class);
            // 保存数据
            String prompt = requestVo.getPrompt();
            RequestEntity requestEntity = new RequestEntity();
            requestEntity.setPrompt(prompt);
            requestEntity.setAnswer(String.valueOf(obj));
            requestService.save(requestEntity);
            System.out.println("------打印响应参数-----" + obj);
            return "6666";
        }
    }
}
